const oss = require("ali-oss");
// const fs = require("fs").promises;
const Sts20150401 = require("@alicloud/sts20150401");
const OpenApi = require("@alicloud/openapi-client");
const Util = require("@alicloud/tea-util");

const client = new oss({
  region: "oss-cn-guangzhou",
  accessKeyId: "LTAI5tPHyK32KfH74mRwWxUo",
  accessKeySecret: "jFC3Mpz4RhwxJMN4I550HezY5DW80c",
  bucket: "cells-plus",
  cname: true,
  endpoint: "https://cdn.cellsplus.top",
});

class Alioss {
  // static async upload(file) {
  //   const now = new Date();
  //   const year = now.getFullYear(); // 获取年份
  //   const month = String(now.getMonth() + 1).padStart(2, "0"); // 获取月份，月份从0开始计数，所以要+1，并使用padStart确保是两位数
  //   const day = String(now.getDate()).padStart(2, "0");
  //   const ossFileName = `images/${year}-${month}-${day}/${file.filename}`;

  //   let result = await client.put(ossFileName, file.path);
  //   await fs.unlink(file.path);
  //   return result;
  // }

  static async uploadStreamToOSS(url) {
    let arr = [];
    for (let i = 0; i < url.length; i++) {
      let response = await axios({
        method: "get",
        url: url[i],
        responseType: "stream",
      });
      arr.push({
        data: response.data,
        filename: url[i].split("https://cdn.cellsplus.top/")[1],
      });
    }

    for (let i = 0; i < arr.length; i++) {
      await client.put(arr[i].data, arr[i].filename);
    }
  }

  static async del(filename) {
    if (typeof filename !== "string" || filename.length === 0) {
      throw new Error("Invalid filename");
    }
    const avatarImg = [
      "https://cdn.cellsplus.top/images/2024-08-13/1723554346314.png",
      "https://cdn.cellsplus.top/icon/def-avater.png",
    ];
    if (!avatarImg.includes(filename)) {
      await client.delete(filename.split("https://cdn.cellsplus.top/")[1]);
    }
    return;
  }

  static createClient() {
    // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
    // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378664.html。
    let config = new OpenApi.Config({
      accessKeyId: "LTAI5tPHyK32KfH74mRwWxUo",
      accessKeySecret: "jFC3Mpz4RhwxJMN4I550HezY5DW80c",
    });
    // Endpoint 请参考 https://api.aliyun.com/product/Sts
    config.endpoint = `sts.cn-guangzhou.aliyuncs.com`;
    return new Sts20150401.default(config);
  }

  static async stsToken() {
    let client = Alioss.createClient();
    let assumeRoleRequest = new Sts20150401.AssumeRoleRequest({
      durationSeconds: 3600,
      roleArn: "acs:ram::1745519045209859:role/ramoss",
      roleSessionName: "ramoss",
    });
    let runtime = new Util.RuntimeOptions({});

    // 复制代码运行请自行打印 API 的返回值
    const sts = await client.assumeRoleWithOptions(assumeRoleRequest, runtime);

    return sts;
  }

  static async getTag(objectName) {
    const res = await client.getObjectTagging(objectName);
    return res;
  }

  static async delTag(objectName) {
    for (let i = 0; i < objectName.length; i++) {
      try {
        let res = await client.deleteObjectTagging(
          objectName[i].split("https://cdn.cellsplus.top/")[1]
        );
        return res;
      } catch (e) {
        return e;
      }
    }
  }
}

module.exports = {
  Alioss,
};
